package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"zk12.27/api/request"
	"zk12.27/glodal"
	"zk12.27/internal/model"
)

func LiveAdd(c *gin.Context) {
	var req request.LiveAdd
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	live := model.Live{
		LiveName:     req.LiveName,
		LiveDescribe: req.LiveDescribe,
		LiveLookSum:  req.LiveLookSum,
		LiveFire:     req.LiveFire,
	}
	err = glodal.DB.Create(&live).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播间创建失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live.ID,
	})
}

func LiveList(c *gin.Context) {
	var req request.LiveList
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	err = glodal.DB.Where("id = ?", req.LiveId).First(&live).Error
	if live.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live,
	})
}

func LiveUpdate(c *gin.Context) {
	var req request.LiveUpdate
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	live := model.Live{
		Model:        gorm.Model{ID: req.LiveId},
		LiveName:     req.LiveName,
		LiveDescribe: req.LiveDescribe,
	}
	err = glodal.DB.Updates(&live).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播间修改失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live,
	})
}

func LiveDelete(c *gin.Context) {
	var req request.LiveDelete
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	err = glodal.DB.Where("id = ?", req.LiveId).First(&live).Error
	if live.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	err = glodal.DB.Delete(&live).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播间删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live.ID,
	})
}
